import modelExtend from 'dva-model-extend'
import {config} from 'utils'
import * as articleService from './service'
import {pageModel} from 'utils/model'

const {
  findAllArticle,
  insertArticle,
  removeArticle,
  removeArticles,
  updateArticle,
  findAllPubArticle,
  insertArticlePub,
  removeArticlePub,
  removesArticlePub,
  findPortletToPub,
  // getPubTarget,
} = articleService

const {prefix} = config

export default modelExtend(pageModel, {
  namespace: 'contentArticle',
  state: {

    selectedRowKeysPub: [],
    isMotion: window.sessionStorage.getItem(`${prefix}userIsMotion`) === 'true',

    editContentId: 'editor0', // TODO id
    editInitialContent: '', // 初始内容
    editHtmlContent: '', // html 格式的内容
    isPubModal: false, // 发布modal
    modalPubTreeDataToWHo: [], // 发布单位
    modalPubTreeDataAddress: [], // 发布位置，如portlet等

    // TODO new design
    tabPaneKey: '1', // tab key，默认第一个 tab 被选中
    selectedRowKeys: [],
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    pubModalVisible: false,

  },

  subscriptions: {
    setup ({dispatch, history}) {
      history.listen((location) => {
        if (location.pathname === '/content/article') {
          const payload = location.query || {page: 1, pageSize: 10}
          dispatch({
            type: 'query',
            payload,
          })
        }
      })
    },
  },

  effects: {
    // 默认查询全部文章
    * query ({payload = {queryType: 'all'}}, {call, put}) {
      const data = yield call(findAllArticle, payload)
      if (data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data,
            selectedRowKeys: [],
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.total,
            },
          },
        })
      }
    },
    // 获取发布的文章
    * getArticlePubModel ({payload = {}}, {call, put}) {
      const data = yield call(findAllPubArticle, payload)
      if (data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list2: data.data,
            selectedRowKeysPub: [],
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10, //渲染有问题
              total: data.total,
            },
          },
        })
      }
    },
    * delete ({payload}, {call, put, select}) {
      const data = yield call(removeArticle, {id: payload})
      const {selectedRowKeys} = yield select(_ => _.contentArticle)
      if (data.success) {
        yield put({type: 'updateState', payload: {selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload)}})
      } else {
        throw data
      }
    },
    // TODO 发布table删除
    * deletePub ({payload}, { call, put, select}) {
      const data = yield call(removeArticlePub, payload)
      const {selectedRowKeysPub} = yield select(_ => _.contentArticle)
      if (data.success) {
         yield put({type: 'updateState', payload: {selectedRowKeysPub: selectedRowKeysPub.filter((_, i) => {
          return _ !== payload.pgPletId
         })}})
        //  const {list2} = yield select(state => state.contentArticle.list2)
        //  console.log(list2)
      } else {
        throw data
      }
    },
    * multiDelete ({payload}, {call, put}) {
      const data = yield call(removeArticles, payload)
      if (data.success) {
        yield put({type: 'updateState', payload: {selectedRowKeys: []}})
      } else {
        throw data
      }
    },

    * create ({payload}, {call, put}) {
      const data = yield call(insertArticle, payload)
      if (data.success) {
        console.log("create success")
        yield put({type: 'hideModal'})
      } else {
        throw data
      }
    },

    * update ({payload}, {select, call, put}) {
      // const id = yield select(({user}) => user.currentItem.id)
      // const newUser = {...payload, id}
      // const data = yield call(updateArticle, newUser)
      const data = yield call(updateArticle, payload)
      if (data.success) {
        yield put({type: 'hideModal'})
      } else {
        throw data
      }
    },

    // TODO 发布文章
    * insertPubArticleModel ({payload}, {select, call, put}) {
      const data = yield call(insertArticlePub, payload)
      if (data) {
        yield put({
          type: 'hidePubModal',
          payload: {
            modalPubTreeData: [],
          },
        })
      }
    },

    // 批量删除已发布的文章记录
    * multiDeletePub ({payload}, {call, put}) {
      const data = yield call(removesArticlePub, payload)
      if (data.success) {
        yield put({type: 'updateState', payload: {selectedRowKeysPub: []}})
      } else {
        throw data
      }
    },

    // TODO 获取发布单位
    * getPub ({payload}, {select, call, put}) {
      const data = yield call(findPortletToPub, payload)
      if (data) {
        yield put({
          type: 'showPubModal',
          payload: {
            modalPubTreeDataToWho: data.data.toWho,
            modalPubTreeDataAddress: data.data.address,
            modalType: 'publish',
          },
        })
      }
    },

  },

  reducers: {
    // 发布按钮，显示modal
    showPubModal (state, {payload}) {
      return {...state, ...payload, PubmodalVisible: true}
    },
    // 发布完成隐藏modal
    hidePubModal (state, {payload}) {
      return {...state, ...payload, PubmodalVisible: false}
    },
    editorContentUpdate (state, {payload}) {
      return {...state, ...payload}
    },

    // clearSelectKeys (state) {
    //   return {...state, selectedRowKeys: []}
    // },

    editEditorInstanceUpdate (state, {payload}) {
      return {...state, ...payload}
    },

    switchIsMotion (state) {
      window.sessionStorage.setItem(`${prefix}userIsMotion`, !state.isMotion)
      return {...state, isMotion: !state.isMotion}
    },

    // 打开发布modal
    switchArticlePubModal (state) {
      return {...state, isPubModal: !state.isPubModal}
    },


    // TODO new design
    // 切换tab时更新 tab key
    changeTabNum (state, {payload}) {
      return {...state, payload}
    },
    // 创建按钮，显示modal
    showModal (state, {payload}) {
      return {...state, ...payload, modalVisible: true}
    },
    // 创建完成按钮，隐藏modal
    hideModal (state, {payload}) {
      return {...state, ...payload, modalVisible: false}
    },

  },
})
